<template>
    <div class="container1">
        <div class="main">
            <div class="main_up" >
                <div v-if="curUserName == ''">
                    <el-button type="primary" plain @click="openDialog('咨询师登录')">咨询师登录</el-button>


                    <a href="/#/home">
                        <el-button type="primary" plain @click="loginOut">返回</el-button>
                    </a>


                    <a>
                        <el-button type="primary" plain @click="open1">使用说明</el-button>
                    </a>
                </div>
                <div v-else>
                    {{this.curUserName}}
                    <a>
                        <el-button type="primary" plain @click="loginOut">注销</el-button>
                    </a>

                    <a href="/#/home">
                        <el-button type="primary" plain @click="loginOut">返回</el-button>
                    </a>
                    <a >
                        <el-button type="primary" plain @click="open1">使用说明</el-button>
                    </a>
                </div>

            </div>
            <div class="main_down">
                <!--            <div class="left1">-->
                <!--                <div class="left_down">-->
                <!--                    <div class="label_title">-->
                <!--                        可聊天用户-->
                <!--                        <i class="el-icon-user-solid"></i>-->
                <!--                    </div>-->

                <!--                    <div v-for="item in sessionList_not" :key="item.stuId" class="box"-->
                <!--                         @click="createSession(item.consultId, item.consultName)">-->
                <!--                        <div class="box_left">-->
                <!--                            {{item.consultName}}-->
                <!--                        </div>-->
                <!--                        <i class="el-icon-chat-dot-square" @click="createSession(item.consultId, item.consultName)"></i>-->
                <!--                    </div>-->

                <!--                    <div v-for="item in AllsessionList_not" :key="item.stuId" class="box"-->
                <!--                         @click="createAllSession(item.stuId, item.stuName)">-->
                <!--                        <div class="box_left">-->
                <!--                            {{item.stuName}}-->
                <!--                        </div>-->
                <!--                        <i class="el-icon-chat-dot-square" @click="createAllSession(item.stuId, item.stuName)"></i>-->
                <!--                    </div>-->



                <!--                </div>-->

                <!--            </div>-->
                <div class="left2">
                    <div class="left_up">
                        <div class="label_title">
                            会话
                            <i class="el-icon-user"></i>
                        </div>
                        <div :class="curSessionId == item.id ? 'box_select' : 'box'" v-for="item in sessionList_already"
                             :key="item.id">
                            <div class="box_left" @click="startSession(item.id)">
                                {{item.listName}}
                            </div>
                            <div class="right_left">
                                <div class="right_left_count">
                                    {{item.unReadCount}}
                                </div>

                                <!--                            <div class="right_left_del">-->

                                <!--                                <i class="el-icon-delete" @click="delSession(item.id)"></i>-->
                                <!--                            </div>-->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="right">


                    <div class="up" ref="element" id="msg_end">
                    <div v-for="(item,i) in list" :key="i"
                             :class="item.fromUserId === curUserId ? 'msg_right' : 'msg_left'">
                            <div class="msg_right_up">

                                {{item.fromUserName}}

                            </div>

                            <div :class="item.fromUserId === curUserId ? 'comment_right' : 'comment_left'">
                                <div :class="item.fromUserId === curUserId ? 'msg_right_down' : 'msg_left_down'">
                                    {{item.content}}
                                </div>
                            </div>
                        </div>

                    </div>
                    <div class="down">
                        <el-input
                                type="textarea"
                                :rows="3"
                                placeholder="请输入内容，回车发送！"
                                @keyup.enter.native="sendMsg"
                                v-model="textarea">
                        </el-input>

                        <el-button @click="sendMsg">发送</el-button>

                    </div>
                </div>
            </div>

            <el-dialog
                    v-model="dialogVisible"
                    width="20%"
            >
                <el-input v-model="loginName" placeholder="请输入用户名"></el-input>
                <span style="color: red;">咨询师1</span>

                <el-input placeholder="请输入密码" v-model="consultPwd" show-password></el-input>
                <span style="color: red;">123</span>


                <template #footer>
            <span class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="ConsultloginOrRegister">确 定</el-button>
			</span>
                </template>
            </el-dialog>
        </div>


    </div>
</template>

<script>
    import axios from 'axios';
    import {ElMessage} from "element-plus";

    export default {

        name: 'Chat',
        data() {
            return {
                dialogVisible: false,
                dialogTitle: '',
                loginName: '',
                textarea: "",
                list: [],
                curUserId: "",
                curUserName: "",
                curSessionId: '',
                sessionList_already: [],
                sessionList_not: [],
                AllsessionList_not: [],
                consultPwd:[],
            }
        },
        created() { // 页面创建生命周期函数
            this.IsUser();
        },
        updated() {
            // 解决每次发消息到最后面
            var elmnt = document.getElementById("msg_end");
            elmnt.scrollTop = elmnt.scrollHeight;
        },
        destroyed: function () { // 离开页面生命周期函数
            this.websocketclose();
        },
        methods: {

            IsUser(){
                var param = sessionStorage.getItem('aTokenofAStrangeUser');
                this.$axios
                    .post("http://49.232.135.8:8088/back/userinfo/isouruser",param)
                    .then(rst=>{
                        if(rst.data!="")
                        {
                            this.loginName=rst.data.stuName;
                            this.loginOrRegister()

                        }
                    }).catch(ex=>{
                    console.log(ex);
                });
            },
            initWebSocket: function (userId, sessionId) {
                // 和后端建立连接
                this.websock = new WebSocket("ws://49.232.135.8:8088/back/websocket/" + userId + "/" + sessionId);
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen: function () {
                console.log("WebSocket连接成功");
            },
            websocketonerror: function (e) {
                console.log("WebSocket连接发生错误", e);
            },
            websocketonmessage: function (e) {
                let data = JSON.parse(e.data);
                if (data instanceof Array) {
                    // 列表数据
                    this.sessionList_already = data
                } else {
                    // 消息数据
                    this.list.push(data)
                }
            },
            websocketclose: function (e) {
                if (this.curUserId != null) {
                    if (this.curSessionId != null) {
                        this.initWebSocket(this.curUserId, this.curSessionId)
                    } else {
                        this.initWebSocket(this.curUserId, 99999999)
                    }
                }
                console.log("connection closed", e);
                console.log(e);
            },
            // 消息发送
            sendMsg() {
                let thus = this;
                console.log(thus.curSessionId);
                if (thus.curSessionId == 99999999) {
                    return this.$message.error("请选择左边的对话框开始聊天!")
                }
                let data = {
                    "fromUserId": this.curUserId,
                    "fromUserName": this.curUserName,
                    "content": this.textarea
                };

                axios.get('http://49.232.135.8:8088/back/sessionList/select?id=' + this.curSessionId)
                    .then(function (response) {
                        if(response.data.msg == "小冰(机器人)")
                        {
                            axios.get('http://49.232.135.8:8088/back/keyword?keyword=' + data['content'])
                                .then(function (response1) {
                                    var s=response1.data.msg;
                                    if(s==null)
                                    {
                                        s="很抱歉，无法识别你的问题，如需更多帮助，请转咨询师服务"
                                    }

                                    let data = {
                                        "fromUserId": 999,
                                        "fromUserName": "小冰(机器人)",
                                        "content": s
                                    };

                                    thus.list.push(data)

                                })
                                .catch(function (error) {
                                    console.log(error);
                                });

                        }
                        else {
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                this.list.push(data);
                this.websock.send(this.textarea);
                this.textarea = ''
            },
            openDialog(openName) {
                this.dialogTitle = openName
                this.dialogVisible = true
            },
            open1() {
                this.$alert('普通用户登录需要在首页点击登录，然后点击在线聊天，' +
                    '此页面仅供咨询师登录, ' +
                    '在另外客户端或者新开一个页面普通用户和咨询师可以相互发送消息，实现咨询师功能', '使用说明', {
                    confirmButtonText: '确定',
                });
            },

            // 登录or注册
            loginOrRegister() {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/login?name=' + thus.loginName)
                    .then(function (response) {
                        thus.$message.success("登录成功");
                        thus.curUserId = response.data.data.stuId;
                        thus.curUserName = response.data.data.stuName;
                        thus.dialogVisible = false;
                        thus.getSessionListNot();
                        thus.sessionListAlready();
                        thus.startSession(99999999)
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },

            ConsultloginOrRegister() {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/consultlogin?name=' + thus.loginName+"&consultPwd=" + thus.consultPwd)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.$message.success("登录成功");
                        thus.curUserId = response.data.data.consultId;
                        thus.curUserName = response.data.data.consultName;
                        thus.dialogVisible = false;
                        thus.getAllSessionListNot();
                        thus.sessionListAlready();
                        thus.startSession(99999999)

                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 获取咨询师可建立会话列表
            getSessionListNot() {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/sessionList/not?id=' + this.curUserId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.sessionList_not = response.data.data
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 获取所有人可建立会话列表
            getAllSessionListNot() {
                let thus = this
                axios.get('http://49.232.135.8:8088/back/sessionAllList/not?id=' + this.curUserId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.AllsessionList_not = response.data.data
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 获取已存在的会话列表
            sessionListAlready() {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/sessionList/already?id=' + this.curUserId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.sessionList_already = response.data.data
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 创建会话
            createSession() {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/createSession?id=' + this.curUserId +"&userIdName=" + thus.curUserName)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        // console.log(response);
                        thus.getSessionListNot();
                        thus.sessionListAlready()
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },

            createAllSession(toUserId, toUserName) {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/createAllSession?id=' + this.curUserId +"&userIdName=" + thus.curUserName+ "&toUserId=" + toUserId + "&toUserName=" + toUserName)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.getAllSessionListNot()
                        thus.sessionListAlready()
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 开始会话
            startSession(sessionId) {
                if (this.websock != undefined) {
                    this.websock.close()
                }
                this.curSessionId = sessionId;
                this.initWebSocket(this.curUserId, sessionId);
                this.msgList(sessionId)
            },
            // 删除会话
            delSession(sessionId) {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/delSession?sessionId=' + sessionId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        axios.get('http://49.232.135.8:8088/back/sessionList/searchConsult?name=' + thus.curUserName)
                            .then(function (response) {
                                if (response.data.msg == null) {
                                    thus.getSessionListNot();
                                    thus.sessionListAlready();
                                } else {
                                    thus.getAllSessionListNot();
                                    thus.sessionListAlready();
                                }
                            })
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 退出登录
            loginOut() {
                let thus = this;
                thus.curUserId = '';
                thus.curUserName = '';
                thus.dialogTitle= '';
                thus.loginName= '';
                thus.textarea= "";
                thus.list= [];
                thus.curUserId= "";
                thus.curUserName= "";
                thus.curSessionId= '';
                thus.sessionList_already= [];
                thus.sessionList_not= [];
                thus.AllsessionList_not=[];
                thus.consultPwd=[];
                return thus.$message.success("返回成功");

            },
            // 获取消息数据
            msgList(sessionId) {
                let thus = this;
                axios.get('http://49.232.135.8:8088/back/msgList?sessionId=' + sessionId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.list = response.data.data;
                        // 从新获取列表
                        thus.sessionListAlready()
                    })
                    .catch(function (error) {
                        console.log(error);
                    });


            }
        }
    }
</script>


<style>
    *{
        margin: 0;
        padding: 0;
    }
    html,body{
        width: 100%;
        height: 100%;
        background-image: url(../assets/backimg5.png);
    }
    .container1 {
        height:100%;width:100%;
        /*width: 100%;*/
        position:fixed;
        /*background-color: #fab6b6;*/
    }
    .main {

        width: 100%;
        height: 100%;
    }

    .main_up {
        width: 100%;
        height: 10%;
        padding-top: 5%;
        padding-left: 30%;
    }

    .main_down {
        position: absolute;
        left: 50%;
        top:50%;
        transform: translate(-50%,-50%);
        background-color: #FFF5EE;
        width: 45%;
        height: 63%;
        display: flex;
    }
    /*.left1 {*/

    /*    width: 25%;*/
    /*    height: 100%;*/
    /*    border-right: 1px #909399 solid;*/
    /*    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
    /*    background-color: #FFF5EE;*/
    /*}*/

    .left2 {

        width: 30%;
        height: 100%;
        border-right: 1px #909399 solid;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        background-color: #FFF5EE;
    }

    .left_up {

        width: 100%;
        height: 100%;
        overflow-y: auto;
        border: 1px #909399 solid;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        background-color: #FFF5EE;


        /* border: 1px red solid; */
    }

    .label_title {
        width: 90%;
        height: 9%;
        background-color: #EED8DF;
        font-family: Arial, Helvetica, sans-serif;
        font-weight: 600;
        padding: 10px;

    }
    .label_title1 {
        width: 90%;
        height: 9%;
        background-color: #EED8DF;
        font-family: Arial, Helvetica, sans-serif;
        font-weight: 600;
        padding: 10px;

    }

    .left_down {

        width: 100%;
        height: 100%;
        overflow-y: auto;
        border: 1px #909399 solid;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        /* border: 1px green solid; */

    }

    .right {
        width: 70%;
        height: 100%;

    }

    .box {

        width: 100%;
        height: 8%;
        padding: 10px 25px 10px 25px;
        display: flex;
        justify-self: flex-end;


        /* border: 1px red solid; */
    }

    .box:hover {

        background-color: #D8EAFF;
        cursor: pointer;
    }

    .box_select {

        width: 100%;
        height: 8%;
        padding: 10px 25px 10px 25px;
        display: flex;
        justify-self: flex-end;
        background-color: #D8EAFF;
    }

    .box_left {

        width: 70%;
        height: 100%;

    }

    .right_left {

        width: 30%;
        height: 100%;
        display: flex;
        justify-content: space-between;

        /* border: 1px red solid; */
    }

    .right_left_count {

        /* border: 1px blue solid; */
        padding-left: 49%;
        width: 100%;
    }

    .right_left_del {

        width: 100%;
        padding-left: 49%;
    }

    .up {
        width: 100%;
        height: 100%;
        overflow-y: scroll;
        overflow-x: hidden;
        /* padding-bottom: 40px; */
        border: 1px #909399 solid;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .msg_left {
        width: 100%;
        /* padding-left: 5px; */
        /*margin-top: 3%;*/
        /*padding-left: 3%;*/
        /* border: 1px #1890ff solid; */
    }

    .msg_left_up {
        width: 100%;
        /*margin-top: 5px;*/
        /*padding-left: 3%;*/
    }

    .msg_left_down {
        /*margin-left: 6%;*/
        /*width: 100%;*/
        white-space:normal;
        word-break:break-all;
        display:inline-block;
        *display:inline;
        *zoom:1;
        /*white-space:normal;*/
        /*display:inline-block;*/
        /**display:inline;*/
        /**zoom:1;*/
    }

    .msg_right {
        width: 100%;
        /* padding-right: 20px; */
        margin-top: 5px;
        /* border: 1px #1890ff solid; */
        text-align: right;
    }

    .msg_right_up {
        height: 25px;
        margin-top: 20px;
        padding-right: 20px;


    }

    .msg_right_down {
        /*margin-top: 5px;*/
        /*!* border: 1px #1890ff solid; *!*/
        /*margin-right: 40px;*/
        white-space:normal;
        word-break:break-all;
        display:inline-block;
        *display:inline;
        *zoom:1;
    }

    .down {
        border: 1px #909399 solid;
        width: 100%;
        height: 17%;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);


    }
    .comment_left {
        display:inline-block;
        *display:inline;
        *zoom:1;
        margin-left: 30px;
        position: relative;
        background: #fab6b6;
        border-radius: 4px;
    }
    .comment_right {
        display:inline-block;
        *display:inline;
        *zoom:1;
        margin-right: 30px;
        position: relative;
        background: #90EE90;
        border-radius: 5px;
    }
    .comment_right:after {
        content: '';
        width: 0;
        height: 0;
        position: absolute;
        top: 2px;
        right: -16px;
        border: solid 8px;
        border-color: transparent transparent transparent #90EE90;
        font-size: 0;
    }
    .comment_left:before {
        content:'';
        position:absolute;
        right:100%;
        top:0px;
        width:0;
        height:0;
        border-width:8px;
        border-style:solid;
        border-color:transparent;
        border-right-width:16px;
        border-right-color:currentColor;color:#fab6b6;
    }
</style>
